package com.yike.user.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yike.common.exception.BusinessException;
import com.yike.common.pagination.PageInfo;
import com.yike.common.pagination.Paging;
import com.yike.common.tool.LoginUtil;
import com.yike.common.tool.StringUtil;
import com.yike.user.entity.Agent;
import com.yike.user.entity.User;
import com.yike.user.mapper.AgentMapper;
import com.yike.user.mapper.UserMapper;
import com.yike.user.param.PlatformAgentPageParam;
import com.yike.user.param.PlatformAgentParam;
import com.yike.user.service.PlatformAgentService;
import com.yike.user.vo.PlatformAgentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 平台用户 服务实现类
 *
 * @author Sakura
 * @since 2024-10-29
 */
@Slf4j
@Service
public class PlatformAgentServiceImpl implements PlatformAgentService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AgentMapper agentMapper;

    @Override
    public boolean addAgent(PlatformAgentParam platformAgentParam) throws Exception {
        // 添加代理商时需要判断当前联系人手机号是否已存在账号，如果不存在先添加账号
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getMobile, platformAgentParam.getMobile()));
        if (user == null) {
            // 如果用户不存在则创建一个用户
            user = new User();
            BeanUtils.copyProperties(platformAgentParam, user);
            user.setUserNo(StringUtil.random(32)); // 生成用户ID
            user.setNickname(platformAgentParam.getContact());
            user.setCreateBy(LoginUtil.getUserId());
            userMapper.insert(user);
        }

        // 判断当前用户是否已是代理商
        Agent agent = agentMapper.selectOne(Wrappers.lambdaQuery(Agent.class)
                .eq(Agent::getUserId, user.getId()));
        if (agent != null) {
            throw new BusinessException("当前用户已是代理商，请勿重复添加");
        }

        // 增加一条代理商记录
        agent = new Agent();
        BeanUtils.copyProperties(platformAgentParam, agent);
        agent.setAgentNo("66" + StringUtil.getStrNo());
        agent.setUserId(user.getId());
        agent.setCreateBy(LoginUtil.getUserId());

        // 如果上级代理商编号不为空需要验证上级代理商
        if (platformAgentParam.getParentId() != null && platformAgentParam.getParentId() != 0) {
            // 获取上级代理商信息
            Agent parentAgent = agentMapper.selectById(platformAgentParam.getParentId());
            if (parentAgent == null) {
                throw new BusinessException("上级代理商信息异常");
            }
            agent.setParentId(parentAgent.getId());
        }
        agentMapper.insert(agent);

        return true;
    }

    @Override
    public boolean updateAgent(PlatformAgentParam platformAgentParam) throws Exception {
        // 获取代理商信息
        Agent agent = agentMapper.selectById(platformAgentParam.getId());
        if (agent == null) {
            throw new BusinessException("代理商信息异常");
        }

        // 获取代理商用户信息
        User user = userMapper.selectById(agent.getUserId());
        if (user == null) {
            throw new BusinessException("代理商账号信息异常");
        }

        // 判断联系人和手机号是否改变
        if (!platformAgentParam.getContact().equals(user.getNickname()) || !platformAgentParam.getMobile().equals(user.getMobile())) {
            // 如果手机号发生改变需要新手机号不能存在账号
            if (!platformAgentParam.getMobile().equals(user.getMobile())) {
                User checkUser = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                        .eq(User::getMobile, platformAgentParam.getMobile()));
                if (checkUser != null) {
                    throw new BusinessException("当前手机号已存在账号信息");
                }
                user.setMobile(platformAgentParam.getMobile());
            }

            user.setNickname(platformAgentParam.getContact());
            userMapper.updateById(user);

            // 此处清空不修改店铺本身的联系人信息，因为店铺可能是商家自己创建的
            platformAgentParam.setContact(null);
            platformAgentParam.setMobile(null);
        }

        // 如果上级代理商编号不为空需要验证上级代理商
        if (platformAgentParam.getParentId() != null && platformAgentParam.getParentId() != 0) {
            // 获取上级代理商信息
            Agent parentAgent = agentMapper.selectById(platformAgentParam.getParentId());
            if (parentAgent == null) {
                throw new BusinessException("上级代理商信息异常");
            }
            agent.setParentId(parentAgent.getId());
        }

        BeanUtils.copyProperties(platformAgentParam, agent);
        agent.setUpdateBy(LoginUtil.getUserId());
        agentMapper.updateById(agent);

        return true;
    }

    @Override
    public boolean deleteAgent(Long id) throws Exception {
        // 获取代理商信息
        Agent agent = agentMapper.selectById(id);
        if (agent == null) {
            throw new BusinessException("代理商信息异常");
        }
        agentMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean batchDel(List<Long> ids) throws Exception {
        agentMapper.deleteBatchIds(ids);
        return true;
    }

    @Override
    public PlatformAgentVo getAgent(Long id) throws Exception {
        return agentMapper.getPlatformAgentVo(id);
    }

    @Override
    public Paging<PlatformAgentVo> getAgentPageList(PlatformAgentPageParam platformAgentPageParam) throws Exception {
        Page<Agent> page = new PageInfo<>(platformAgentPageParam);
        IPage<PlatformAgentVo> iPage = agentMapper.getPlatformAgentList(page, platformAgentPageParam);
        return new Paging<PlatformAgentVo>(iPage);
    }
}
